package com.example.shop

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.ProductEntityItem
import com.example.base.net.ShopApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

/**
 * 数据源
 */
class ProductDataSource(val shopApiService: ShopApiService):PagingSource<Int,ProductEntityItem>() {
    //刷新
    override fun getRefreshKey(state: PagingState<Int, ProductEntityItem>): Int? {
        return null
    }
    //加载
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ProductEntityItem> {
        //涉及到网络请求一律在子线程中请求   try-catch考虑网路问题
       return withContext(Dispatchers.IO){
           try {
               //当前页面  每页请求条数
               val key = params.key?:1
               val limit = 5
               //请求数据
               val res = shopApiService.product(limit, key).first()
               //判断是否有下一页
               //val nextKey = if(res.data.totalPage>key) key+1 else null
               if(res.code==200){
                   //加载数据
                   LoadResult.Page(res.data.list,null,key+1)
               }else{
                   //加载数据失败
                   LoadResult.Error(Exception(res.message))
               }
           } catch (e: Exception) {
               LoadResult.Error(Exception(e))
           }
       }

    }
}